import axios from "axios";
import LoginApi from "./login.js";
import { API_BASE_URL } from "../config";

const apiService = axios.create({
    baseURL: API_BASE_URL
});
const NETWORK_ERROR = "网络错误...";

// 请求前
apiService.interceptors.request.use((config) => {
    config.headers.Authorization = "Bearer " + localStorage.getItem("token");
    return config;
}, (error) => {
    return Promise.reject(error);
});

// 请求后
apiService.interceptors.response.use((res) => {
    if (res.status !== 200) {
        // 处理非200状态码
        ElMessage({
            message: res.data || NETWORK_ERROR + ":" + res.status,
            type: "error"
        });
        return res.data;
    }

    // 处理200状态码
    if (res.data && res.data.url && res.data.domain){
        // 上传图片成功
        return res.data;
    }

    // 处理其他200状态码
    if (res.data && res.data.code !== 0){
        ElMessage({
            message: res.data.msg || NETWORK_ERROR + ":" + res.status,
            type: "error"
        });
    }

    return res.data;
}, async (error) => {
    if (!error.response){
        ElMessage({
            message: NETWORK_ERROR,
            type: "error"
        });
        return Promise.reject(error);
    }
    if (error.response.status === 401) {
        const refreshToken = localStorage.getItem("refresh")

        if (refreshToken === 'undefined'){
            ElMessage({
                message: "登录已过期，请重新登录",
                type: "error"
            });
            localStorage.removeItem("token");
            localStorage.removeItem("refresh");
            window.location.href = "/login";
            refreshToken = '';
        }
        
        if (refreshToken && !error.config.__isRetryRequest) {
            const data = await LoginApi.refreshToken(refreshToken)
            if (data.code === 0){
                localStorage.setItem("token", data.data.account);
                localStorage.setItem("refresh", data.data.refresh);
                // 重新发起原请求
                const originalRequest = error.config;
                originalRequest.headers.Authorization = "Bearer " + data.data.account;
                return apiService(originalRequest);
            }
        }else {
            localStorage.removeItem("token");
            localStorage.removeItem("refresh");
            console.log("过期");
            ElMessage({
                message: "登录已过期，请重新登录",
                type: "error"
            });
            window.location.href = "/login";
        }
    }
    return Promise.reject(error);
});


// 不填method默认是get
function request(options) {
    options.method = options.method || "get";
    return apiService(options);
}
export default request;